import 'package:chat/common/service/HttpService.dart';
import 'package:chat/common/utils/storage.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../../../common/routers/names.dart';

class LoginController extends GetxController {
  // 登录账号
  final TextEditingController userNameController = TextEditingController();

  // 登录密码
  final TextEditingController passwordController = TextEditingController();

  RxBool isObscure = true.obs;

  /// 登录
  Future<void> login() async {
    final username = userNameController.text.trim();
    final password = passwordController.text.trim();

    // 输入校验
    if (username.isEmpty) {
      EasyLoading.showError("请输入用户名");
      return;
    }
    if (password.isEmpty) {
      EasyLoading.showError("请输入密码");
      return;
    }

    try {
      final response = await HttpService.to.post("/user/username/login", data: {"username": username, "password": password});

      if (response.statusCode == 200 && response.data["code"] == 200) {
        EasyLoading.showSuccess("登录成功");
        // 保存用户数据
        await Storage().setJson("user", response.data["data"]["user"]);
        // 保存token
        final accessToken = response.data["data"]["access_token"];
        final refreshToken = response.data["data"]["refresh_token"];
        await Storage().saveTokens(accessToken, refreshToken);
        Get.offAllNamed(RouteNames.main);
      } else {
        EasyLoading.showError(response.data["msg"] ?? "登录失败");
      }
    } catch (e) {
      EasyLoading.showError("用户名登录异常，请稍后再试");
      debugPrint("用户名登录异常: $e");
    }
  }

  @override
  void onReady() {
    super.onReady();
    update(["login"]);
  }

  @override
  void onClose() {
    userNameController.dispose();
    passwordController.dispose();
    super.onClose();
  }
}
